package app.caihan.wanandroid.ui.article

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.ViewGroup
import androidx.lifecycle.Observer
import app.caihan.scframe.common.loadinghelper.ToolbarConfig
import app.caihan.scframe.common.loadinghelper.ToolbarType
import app.caihan.scframe.databind.DataBindingConfig
import app.caihan.scframe.ktx.setSingleOnItemClickListener
import app.caihan.wanandroid.BR
import app.caihan.wanandroid.R
import app.caihan.wanandroid.base.WanBaseActivity
import app.caihan.wanandroid.viewmodel.ArticleListUiModel
import org.jetbrains.anko.toast


class ArticleListUi : WanBaseActivity<ArticleListUiModel>() {
    private val mAdapter by lazy { ArticleListAdapter() }

    companion object {

        fun startArticleList(content: Context) {
            val intent = Intent().apply {
                setClass(content, ArticleListUi::class.java)
            }
            content.startActivity(intent)
        }
    }

    override fun useBaseToolbar(): ToolbarConfig {
        return ToolbarConfig(ToolbarType.TOOLBAR, "帖子列表")
    }

    override fun getDataBindingConfig(): DataBindingConfig {
        return DataBindingConfig(BR.vm)
            .addBindingParam(BR.adapter, mAdapter)
    }


    override fun bindLayoutId(): Int {
        return R.layout.activity_article_list_ui
    }

    override fun initView(savedInstanceState: Bundle?) {
        mAdapter.apply {
            setSingleOnItemClickListener { adapter, view, position ->
                val item = mAdapter.data[position]
                toast("点击了${item.author} 的 ${item.title}")
            }
        }
    }

    override fun createObserver() {
        mViewModel.run {
            articleList.observe(this@ArticleListUi, Observer {
                if (it.curPage == 1) {
                    mAdapter.setList(it.datas)
                } else {
                    mAdapter.addData(it.datas)
                }
            })
        }
        mViewModel.autoRefresh()
    }


    private fun forData(llRoot: ViewGroup) {
        val childCount = llRoot.childCount
        for (i in 0 until childCount) {
            if (llRoot.getChildAt(i) is ViewGroup) {
                Log.e("打印ViewGroup", "= ${llRoot.getChildAt(i)}")
                forData(llRoot.getChildAt(i) as ViewGroup)
            } else {
                Log.e("打印View", "= ${llRoot.getChildAt(i)}")
            }
        }
    }
}

